package userInfoController

import (
	"iristest/common/date"
	"iristest/common/log"
	"iristest/common/middleware"
	"iristest/common/res"
	"iristest/do/user"
	"iristest/service/userInfoService"
	"strconv"

	"github.com/kataras/iris/mvc"
	"github.com/kataras/iris/v12"
)

type Controller struct {
	iuis userInfoService.IUserInfoService
}

func New() *Controller {
	return &Controller{
		iuis: userInfoService.New(),
	}
}
func (c *Controller) BeforeActivation(b mvc.BeforeActivation) {
}

func (c *Controller) PostUpdate(ctx iris.Context) res.Result {
	iti, _ := ctx.User().GetRaw()
	ti := iti.(*middleware.TokenInfo)
	if ti == nil {
		log.Ex("读取token失败")
		return res.NoLogins("读取token失败")
	}
	userId := ti.UserId
	if userId == 0 {
		log.Ex("从token中读取id失败")
		return res.NoLogins("读取id失败")
	}
	name := ctx.URLParam("name")
	photo := ctx.URLParam("photo")
	sex := ctx.URLParam("sex")
	birthday := ctx.URLParam("birthday")
	u := user.UserInfo{}
	u.UserId = userId
	if len(name) != 0 {
		u.Name = name
	}
	if len(photo) != 0 {
		u.Photo = photo
	}
	if len(sex) != 0 {
		_sex, err := strconv.ParseInt(sex, 10, 8)
		if err != nil {
			log.Err(err, "修改信息时性别转int失败")
			return res.FormatErrors("性别格式不正确")
		}
		u.Sex = int8(_sex)
	}
	if len(birthday) != 0 {
		_birthday, err := date.DateToUnix(birthday)
		if err != nil {
			log.Err(err, "修改信息时生日转unix错误")
			return res.FormatErrors("生日格式不正确")
		}
		u.Birthday = _birthday
	}
	return c.iuis.Update(&u)
}

func (c *Controller) DeleteDel(ctx iris.Context) res.Result {
	return c.iuis.DelForge(ctx)
}
func (c *Controller) DeleteDelr(ctx iris.Context) res.Result {
	return c.iuis.Del(ctx)
}
func (c *Controller) GetQuerys() res.Result {
	return c.iuis.Querys()
}
